// src/components/PointsRankChart.jsx
import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

const PointsRankChart = ({ rankList, yourUsername }) => {
  const chartRef = useRef(null);

  useEffect(() => {
    if (!rankList || rankList.length === 0) return;

    const myChart = echarts.init(chartRef.current);

    const usernames = rankList.map((item) => item.username);
    const points = rankList.map((item) => item.current_points);

    const highlightIndex = rankList.findIndex((item) => item.username === yourUsername);

    const option = {
      title: {
        text: '积分排行榜',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: {
        type: 'category',
        data: usernames,
        axisLabel: {
          rotate: 30,
        },
      },
      yAxis: {
        type: 'value',
        name: '积分',
      },
      series: [
        {
          name: '积分',
          type: 'bar',
          data: points.map((value, index) => ({
            value,
            itemStyle: {
              color: index === highlightIndex ? '#f56c6c' : '#409eff',
            },
          })),
        },
      ],
    };

    myChart.setOption(option);
    window.addEventListener('resize', myChart.resize);

    return () => {
      myChart.dispose();
      window.removeEventListener('resize', myChart.resize);
    };
  }, [rankList, yourUsername]);

  return <div ref={chartRef} style={{ width: '100%', height: 400 }} />;
};

export default PointsRankChart;
